<template>
  <div class="container">
    <div class="flex-container">
      <label class="file-input-label">
        <input
          type="file"
          @change="onFileChange"
          accept="image/*"
          class="custom-input"
        />
        选择图片
      </label>
      <div>
        <button
          @click="performOCR"
          :disabled="!selectedFile"
          class="custom-button"
        >
          执行OCR
        </button>
      </div>
    </div>
    <div v-if="selectedFile" class="image-preview">
      <img :src="previewURL" alt="预览" class="preview-image" />
    </div>
    <div v-if="ocrResult" class="ocr-result">
      <h1>OCR结果</h1>
      <p class="result-text">{{ ocrResult }}</p>
    </div>
  </div>
</template>

<script>
import Tesseract from "tesseract.js";

export default {
  data() {
    return {
      selectedFile: null,
      previewURL: null,
      ocrResult: "",
    };
  },
  methods: {
    // 选择文件后触发
    onFileChange(event) {
      this.selectedFile = event.target.files[0];
      this.previewURL = URL.createObjectURL(this.selectedFile);
    },
    // 执行OCR
    performOCR() {
      if (!this.selectedFile) return;
      // 使用Tesseract.js执行OCR
      // 设置识别语言为英文 eng 你可以根据需要更改为其他语言代码
      // 例如中文为 chi_sim
      // 多语言识别，通过 + 连接，例如中英文识别为 "eng+chi_sim"
        Tesseract.recognize(
          this.selectedFile,
          "eng+chi_sim",
          { logger: (info) => console.log(info) } // 可选参数，用于输出调试信息
        )
          .then(({ data: { text } }) => {
            console.log("OCR结果");
            console.log(text);
            this.ocrResult = text;
          })
          .catch((error) => {
            console.error("OCR出现错误:", error);
          });
    },
  },
};
</script>
<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 20px;
}

.flex-container {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 20px;
}

.custom-input {
  width: 100px;
  height: 40px;
  display: none; /* 隐藏原生文件输入框 */
}

.file-input-label {
  background-color: #409eff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.file-input-label:hover {
  background-color: #66b1ff;
}

.file-input-label input {
  /* 设置透明度为0，确保隐藏的文件输入框不会影响到label的样式 */
  opacity: 0;
}

.custom-button {
  width: 100px;
  height: 40px;
  background-color: #409eff;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.custom-button:disabled {
  background-color: #c0c4cc;
  cursor: not-allowed;
}

.image-preview {
  margin-top: 20px;
}

.preview-image {
  max-height: 300px;
}

.ocr-result {
  width: 800px;
  margin: 24px auto;
  margin-top: 20px;
}

.result-text {
  font-size: 36px;
  line-height: 36px;
  letter-spacing: 0px;
  word-spacing: 0px;
}
</style>
